package com.shuaidong.site.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.shuaidong.site.common.util.ShiroUtil;
import com.shuaidong.site.entity.SysUser;
import com.shuaidong.site.entity.SysUserRole;
import com.shuaidong.site.mapper.SysUserMapper;
import com.shuaidong.site.mapper.SysUserRoleMapper;
import com.shuaidong.site.service.ISysUserService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.Map;

/**
 * @author td
 * @date 2017/12/22
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper,SysUser> implements ISysUserService {

    /**
     * 用户服务
     */
    @Autowired
    private SysUserMapper userMapper;
    /**
     * 用户角色关系服务
     */
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;


    @Override
    public Page<Map<Object, Object>> selectUserPage(Page<Map<Object, Object>> page, String search) {
        return null;
    }

    @Override
    public void insertUser(SysUser user, String[] roleIds) {

        user.setCreateTime(new Date());
        user.setPassword(ShiroUtil.md51024Pwd(user.getPassword(),user.getUserName()));
        // 保存用户
        userMapper.insert(user);
        // 绑定角色
        if (ArrayUtils.isNotEmpty(roleIds)) {
            for (String rid :roleIds) {
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setUserId(user.getId());
                sysUserRole.setRoleId(rid);
                sysUserRoleMapper.insert(sysUserRole);
            }
        }
    }

    @Override
    public void updateUser(SysUser sysUser, String[] roleIds) {

        // 密码置为null,不让其更新
        sysUser.setPassword(null);

        //更新用户
        this.userMapper.updateById(sysUser);

        //删除已有的权限
        EntityWrapper<SysUserRole> entityWrapper = new EntityWrapper<SysUserRole>();
        entityWrapper.eq("userId",sysUser.getId());
        this.sysUserRoleMapper.delete(entityWrapper);

        // 重新绑定角色
        if (ArrayUtils.isNotEmpty(roleIds)) {
            for (String rd: roleIds) {
                SysUserRole userRole = new SysUserRole();
                userRole.setUserId(sysUser.getId());
                userRole.setRoleId(rd);
                this.sysUserRoleMapper.insert(userRole);
            }
        }
    }

    @Override
    public void delete(String id) {

    }

}
